<template>
  <a-upload
    name="file"
    listType="text"
    :multiple="multipleFlag"
    :action="uploadAction"
    :headers="headers"
    :data="{ filetype: bizPath }"
    :fileList="fileList"
    :disabled="disabled"
    :multipleFlag="multipleFlag"
    :showUploadList="uploadLoading"
    :before-upload="beforeUpload"
    @change="handleChange"
  >
    <a-button :type="butType" v-if="fileList.length < maxFileSize">
      <a-icon :type="icon" />
      {{ text }}
    </a-button>
  </a-upload>
</template>

<script>
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'

const uidGenerator = () => {
  return '-' + parseInt(Math.random() * 10000 + 1, 10)
}
const getFileName = (path) => {
  if (path.lastIndexOf('\\') >= 0) {
    const reg = new RegExp('\\\\', 'g')
    path = path.replace(reg, '/')
  }
  return path.substring(path.lastIndexOf('/') + 1)
}
export default {
  name: 'WFileUpload',
  data() {
    return {
      uploadAction:
        process.env.VUE_APP_API_BASE_URL + 'publicinterface/getUrlbyfile',
      uploadLoading: false,
      headers: {},
      fileList: [],
      previewImage: '',
      hackReset: false,
      previewVisible: false,
    }
  },
  props: {
    text: {
      type: String,
      required: false,
      default: '上传',
    },
    icon: {
      type: String,
      required: false,
      default: 'upload',
    },
    /* 这个属性用于控制文件上传的业务路径 */
    bizPath: {
      type: String,
      required: false,
      default: 'temp',
    },
    value: {
      type: [String, Array],
      required: false,
      default: '',
    },
    maxFileSize: {
      type: Number,
      required: false,
      default: 1,
    },
    disabled: {
      type: Boolean,
      required: false,
      default: false,
    },
    multipleFlag: {
      type: Boolean,
      required: false,
      default: false,
    },
    uploadProgressFlag: {
      type: Boolean,
      required: false,
      default: true,
    },
    butType: {
      type: String,
      required: false,
      default: '',
    },
  },
  watch: {
    value(val) {
      if (val && val.length > 0) {
        console.log('val1' + this.value)
        if (this.value && this.value.length > 0) {
          this.initFileList(JSON.parse(this.value))
        }
        // this.initFileList(JSON.parse(val))
      }
    },
  },
  created() {},
  mounted() {
    this.uploadLoading = this.uploadProgressFlag
    console.log('val' + this.value)
    this.$nextTick(() => {
      const token = storage.get(ACCESS_TOKEN)
      this.headers = { 'X-Access-Token': token }
      if (this.value && this.value.length > 0) {
        this.initFileList(JSON.parse(this.value))
      }
    })
  },
  methods: {
    initFileList(paths) {
      if (!paths || paths.length === 0) {
        this.fileList = []
        return
      }
      const fileList = []
      const arr = paths
      for (var a = 0; a < arr.length; a++) {
        if (arr[a].path) {
          const url = this.$getFileAccessHttpUrl(arr[a].path)
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a].name),
            status: 'done',
            url: url,
            response: {
              status: 'history',
              content: arr[a],
            },
          })
        }
      }
      this.fileList = fileList
    },
    beforeUpload: function (file) {
      return new Promise((resolve, reject) => {
        var fileType = file.type
        const suffix = file.name.substring(file.name.lastIndexOf('.'))
        // if (fileType) {
        //   if (fileType.indexOf('image') < 0 && fileType.indexOf('application/zip') < 0 && fileType.indexOf('excel') < 0 && fileType.indexOf('sheet') < 0 && fileType.indexOf('text/plain') < 0 && fileType.indexOf('application/x-pkcs12') < 0 && fileType.indexOf('application/vnd.ms-powerpoint') < 0 && fileType.indexOf('video/mp4') < 0 && fileType.indexOf('application/vnd.openxmlformats-officedocument') < 0 && fileType.indexOf('application/pdf') < 0 && fileType.indexOf('application/x-zip-compressed') < 0 && fileType.indexOf('application/msword') < 0) {
        //     this.$message.error('文件类型不正确!')
        //     this.fileList = []
        //     return reject(false)
        //   }
        // } else {
        //   if (!(suffix === '.xlsx' || suffix === '.p12' || suffix === '.mp4' || suffix === '.doc' || suffix === '.docx' || suffix === '.xls' || suffix === '.ppt' || suffix === '.pptx' || suffix === '.txt' || suffix === '.pdf' || suffix === '.jpg' || suffix === '.jpeg' || suffix === '.png' || suffix === '.bmp' || suffix === '.zip' || suffix === '.rar'|| suffix === '.mp3')) {
        //     this.$message.error('文件类型不正确!')
        //     this.fileList = []
        //     return reject(false)
        //   }
        // }
        // const isLt2M = file.size / 1024 / 1024 < 20
        // if (!isLt2M) {
        //   this.$message.error('上传的文件必须小于20MB!')
        //   return reject(false)
        // }
        return resolve(true)
      })
    },
    handleChange(info) {
      console.log(this.uploadAction)
      let fileList = info.fileList
      if (this.uploadProgressFlag) {
        if (fileList.length > this.maxFileSize) {
          this.$message.error('超过最大上传数量')
          return
        }
      }
      if (info.file.status === 'done') {
        if (info.file.response.code === '0000') {
          fileList = fileList.map((file) => {
            if (file.response && file.response.result) {
              file.name = file.response.result.fileOldName
              file.url = this.$getFileAccessHttpUrl(
                file.response.result.filePath
              )
              file.path = file.response.result.filePath
            }
            return file
          })
        } else {
          this.handlePathChange()
          this.$message.error(info.file.response.content)
        }
        // this.$message.success(`${info.file.name} 上传成功!`);
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败.`)
      } else if (info.file.status === 'removed') {
        this.handleDelete(info.file)
      }
      this.fileList = fileList
      if (info.file.status === 'done' || info.file.status === 'removed') {
        this.handlePathChange()
      }
    },
    handlePathChange() {
      const uploadFiles = this.fileList
      const arr = []
      if (!this.multipleFlag) {
        const k = {}
        let tmp
        if (uploadFiles[this.fileList.length - 1].response.content) {
          tmp = uploadFiles[this.fileList.length - 1].response.content
          k.name = tmp.name
          k.path = tmp.path
        } else {
          tmp = uploadFiles[this.fileList.length - 1].response.result
          k.name = tmp.fileOldName
          k.path = tmp.filePath
        }
        if (k.name !== undefined && k.path !== undefined) {
          arr.push(k)
        }
      } else {
        for (var a = 0; a < uploadFiles.length; a++) {
          const k = {}
          let tmp
          if (uploadFiles[a].response.content) {
            tmp = uploadFiles[a].response.content
            k.name = tmp.name
            k.path = tmp.path
          } else {
            tmp = uploadFiles[a].response.result
            k.name = tmp.fileOldName
            k.path = tmp.filePath
          }
          if (k.name !== undefined && k.path !== undefined) {
            arr.push(k)
          }
        }
      }
      this.initFileList(arr)
      this.$emit('change', JSON.stringify(arr))
      this.$emit('ok', JSON.stringify(arr))
    },
    handleDelete(file) {
      // 如有需要新增 删除逻辑
      console.log(file)
    },
    handleCancel() {
      this.close()
      this.previewVisible = false
    },
    close() {},
  },
  model: {
    prop: 'value',
    event: 'change',
  },
}
</script>

<style scoped></style>
